<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Validator;
use App\Models\Admin;
use App\Models\AdminGroup;
use App\Models\AdminRule;
use Illuminate\Support\Facades\Session;

class IndexController extends  Controller{

    //进入登录页
    public function getLogin(){
        //判断是否登录
        if(is_null(Session::get('admin'))){
            return view("Admin.Index.login");
        }else{
            return redirect('admin/center/center');
        }
    }

    //执行登录
    public function postLogin(Request $request){
        $postData = $request->all();    //上传上来的所有值
        $rules = [                      //规则
            'username' => 'required',
            'password' => 'required',
        ];
        $messages = [                   //验证失败时的错误消息
            'username.required' => '用户名不能为空！',
            'password.required' => '密码不能为空！',
        ];
        $validation = Validator::make($postData,$rules,$messages);  //执行验证

        if($validation->fails()){   //判断验证是否成功
            return retArray(404,$validation->errors()->first());    //返回验证错误信息
        }
        $map['username'] = $postData['username'];
        $map['password'] = md5($postData['password']);
        $admin = Admin::where($map)->first()->toArray();        //查询账号密码

        if(!is_null($admin)){                        //判断登录信息是否正确
            //查权限
            $group = AdminGroup::find($admin['group_id'])->toArray();
            $rule = json_decode($group['rule']);
            $admin["rule"] = AdminRule::whereIn("rule_id",$rule)->lists('identifying')->toArray();

            Session::put('admin',$admin);
            return retArray(200,'登录成功！');
        }else{
            return retArray(404,'账号或密码错误');
        }
    }

    //注销
    public function getLogout(){
        Session::flush();
        return redirect('admin/index/login');
    }

}